import Node from './node.js'
class LinkedList {
	constructor() {
		this.count = 0
		this.head = null
	}
	push (element) {
		let node = new Node(element)
		if (this.count === 0) {
			this.head = node
		} else {
			let start = 0
			let current = this.head
			while (start++ < this.count - 1) {
				current = current.next
			}
			current.next = node
		}
		this.count++
		return this
	}
	isEmpty () {
		return this.count === 0
	}
	toString () {
		let current = this.head
		let result = current.element
		for (let i = 1; i < this.count; i++) {
			result = `${result},${current.next.element}`
			current = current.next
		}
		return result
	}
	insert (element, index) {
		if (index > this.count || index < 0 || (!index && index !== 0)) {
			return null
		}
		let node = new Node(element)
		if (index === 0) {
			this.head = node
		} else {
			let current = this.head
			let start = 0
			let pervious = null
			while (start++ < index) {
				pervious = current
				current = current.next
			}
			pervious.next = node
			node.next = current
		}
		this.count++
		return this
	}
	indexOf (element) {
		let current = this.head
		for (let i = 0; i < this.count; i++) {
			if (current.element === element) {
				return i
			}
			current = current.next
		}
		return -1
	}
	getElementAt (index) {
		if (index < 0 || index >= this.count || (!index && index !== 0)) {
			return null
		}
		let current = this.head
		for (let i = 0; i < this.count; i++) {
			if (i === index) {
				return current
			}
			current = current.next
		}
		return null
	}
	removeAt (index) {
		if (index < 0 || index >= this.count || (!index && index != 0)) {
			return null
		}
		let current = this.head
		if (index === 0) {
			this.head = current.next
		} else {
			let start = 0
			let pervious = null
			while (start++ < this.count - 1) {
				pervious = current
				current = current.next
			}
			pervious.next = current.next
		}
		this.count--
		return current
	}
	remove (element) {
		this.removeAt(this.indexOf(element))
	}
	update (index, element) {
		if (index < 0 || index >= this.count || (!index && index !== 0)) {
			return null
		}
		let start = 0
		let current = this.head
		while (start++ < index) {
			current = current.next
		}
		current.element = element
	}
	size () {
		return this.count
	}
}
export default LinkedList
